<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-25
 * Time: 14:03
 */
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;

class FormTokenController extends Controller
{
    public function getToken(Request $request)
    {
        $data = $request->input();
        if(empty($data['type'])){
            $result['code'] = '0';
            $result['message'] = '请上传验证码获取类型';
            return response()->json($result);
        }

        $type = $this->getType($data['type']);
        if(!$type){
            $result['code'] = '0';
            $result['message'] = '表单验证码类型错误';
            return response()->json($result);
        }


        $token = $this->createToken($data['user'],$type);
        $result['code'] = '1';
        $result['message'] = '获取成功';
        $result['token'] = $token;
        return response()->json($result);
    }

    /**
     * token类型判断
     * @param $type
     * @return string
     */
    protected function getType($type)
    {
        switch ($type) {
            case '1':
                $result = 'task_token';
                break;
            default:
                $result = "";
                break;
        }

        return $result;
    }

    //创建TOKEN
    public function createToken($user,$type) {
        $code = chr(mt_rand(0xB0,0xF7)).chr(mt_rand(0xA1,0xFE)).chr(mt_rand(0xB0,0xF7)).chr(mt_rand(0xA1,0xFE)).chr(mt_rand(0xB0,0xF7)).chr(mt_rand(0xA1,0xFE));
        $temp['token'] = $this->authcode($code,$user['uid']);
        if($user['guard'] == 'admin'){
            $temp['guard'] = 1;
        }else{
            $temp['guard'] = 2;
        }

        $info = DB::table('form_token')
            ->where('uid',$user['uid'])
            ->where('guard',$temp['guard'])
            ->where('token',$temp['token'])
            ->where('status',1)
            ->first(['token']);
        if(empty($info)){
            $temp['uid'] = $user['uid'];
            $temp['time'] = time();
            $temp['status'] = 1;
            $temp['type'] = $type;


            if(DB::table('form_token')->insert($temp)){
                return $temp['token'];
            }else{
                return $this->createToken($user,$type);
            }
        }else{
            return $this->createToken($user,$type);
        }
    }

    /* 加密TOKEN */
    public function authcode($str,$uid) {
        $key = "XIANRUO";
        $str = substr(md5($str), 8, 10);
        $str1= urlencode(base64_encode(time() . $uid));
        return md5($key . $str . $str1);
    }
}